package avicit.bdp.dms.prm.Integration;

import avicit.bdp.common.base.BaseDAO;
import avicit.bdp.common.service.dao.CommonTypeDao;
import avicit.bdp.common.service.dto.CommonTypeDTO;
import avicit.bdp.common.utils.DateUtils;
import avicit.bdp.common.utils.SpringApplicationContext;
import avicit.bdp.common.utils.enums.CommonTypeEnums;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * 数据源分类消息处理
 *
 * @author xugb
 * @date 2021/11/4 17:56
 */

public class DataSourceTypeHandle extends BaseMessageHandle {
    private static final Logger log = LoggerFactory.getLogger(DataSourceTypeHandle.class);

    private CommonTypeDao dao;

    public DataSourceTypeHandle() {
        dao = SpringApplicationContext.getBean(CommonTypeDao.class);
    }

    @Override
    public void excuteUpdate(List<Map<String, Object>> list) {
        for (Map<String, Object> map : list) {
            CommonTypeDTO dto = convertDto(map);
            dao.updateByPrimaryKey(dto);
        }
    }

    @Override
    public void excuteInsert(List<Map<String, Object>> list) {
        for (Map<String, Object> map : list) {
            CommonTypeDTO dto = convertDto(map);
            CommonTypeDTO oldDto = dao.selectByPrimaryKey(dto.getId());
            if (oldDto != null) {
                dao.updateByPrimaryKey(dto);
            } else {
                dao.insert(dto);
            }

        }
    }

    private CommonTypeDTO convertDto(Map<String, Object> map) {
        String id = MapUtils.getString(map, "id");
        String name = MapUtils.getString(map, "name");
        String parentId = MapUtils.getString(map, "parent_id");
        Integer leaf = MapUtils.getInteger(map, "leaf");
        String remark = MapUtils.getString(map, "remark");
        Integer orderBy = MapUtils.getInteger(map, "order_by");
        String createdBy = MapUtils.getString(map, "created_by");
        String creationDate = MapUtils.getString(map, "creation_date");
        String lastUpdatedBy = MapUtils.getString(map, "last_updated_by");
        String lastUpdateDate = MapUtils.getString(map, "last_update_date");
        CommonTypeDTO dto = new CommonTypeDTO();
        dto.setId(id);
        dto.setName(name);
        dto.setParentId(parentId);
        dto.setType(CommonTypeEnums.DATASOURCE_TYPE);
        dto.setLeaf(leaf);
        dto.setRemark(remark);
        dto.setOrderBy(orderBy);
        dto.setCreatedBy(createdBy);
        dto.setCreationDate(DateUtils.stringToDate(creationDate));
        dto.setLastUpdatedBy(lastUpdatedBy);
        dto.setLastUpdateDate(DateUtils.stringToDate(lastUpdateDate));
        return dto;
    }

    public BaseDAO getDAO() {
        return this.dao;
    }


    @Override
    public String getType() {
        return "dataSourceType";
    }

}
